#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,sys
import logic
import pool
from log import mylog
from xml.dom import minidom
from control.log import mylog

ROOM_XML = 'static/config/room.xml'

class RoomConfig():
    roomid    = None
    roomname  = None
    roomcount = 0

    
class RoomMgt:

    def __init__(self):
        self.Init()
        
    def Init(self):
        mylog.info('Start Init RoomMgt!')
        ret = self.LoadRoomXml(ROOM_XML)
        if not ret:
            mylog.debug('Load xml fail!')
            sys.exit(-1)
        mylog.info('Load xml success!')
        self.CreateRoom()
        mylog.info('End Init RoomMgt')
        
    def LoadRoomXml(self, name):
        
        self.config = []
        if os.path.isfile(name):
            fp = open(name)
            xmldoc = minidom.parse(fp)
        else:
            return False
        handler = xmldoc.getElementsByTagName('room')
        roomlen = len(handler)
        for i in xrange(roomlen):
            ele = RoomConfig()
            ele.roomid    = handler[i].attributes['id'].value.strip()
            ele.roomname  = handler[i].attributes['name'].value.strip().encode('utf-8')
            ele.roomcount = handler[i].attributes['count'].value.strip()
            self.config.append(ele)
        return True

    def CreateRoom(self):
        self.roomdic = {}
        for item in self.config:
            self.roomdic[item.roomid] = Room(item.roomid,item.roomname,item.roomcount)
            mylog.info('Create room success:RoomID->%s'%(item.roomid))
        
    def GetRoombyRoomId(self, roomid):
        return self.roomdic.get(roomid)

    
class Room():

    def __init__(self,id, name, count):
        #roomid
        self.roomid = id
        self.roomname = name
        #onlinelist
        self.cache = pool.Pool()
        #暂时不用，后面再根据需要改动
        self.count = count

    def Login(self,name,gender):
        '''
            gender:
            1:male
            2:female
            3:unknow
        '''
        if gender!='0' and gender!='1':
            mylog.error('Player gender invalid:name(%s),gender(%s)'%(name,gender))
            return False
        ret = self.cache.AddObj(name, gender)
        return ret

    def Logout(self,name):
        self.cache.DelObj(logic.getIDbyName(name))

    def GetList(self):
        tmp = []
        for key in self.cache.dic.keys():
            player = self.cache.dic.get(key)
            tmp.append((player.GetObjName(), player.GetObjSex()))
            mylog.info('GetList:name(%s),gender(%s)'%(player.GetObjName(), player.GetObjSex()))
        mylog.info('Onlinelist roomid:%s,len:%d'%(self.roomid,len(tmp)))
        return tmp
